package model.fshare.client;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;

import model.fshare.Interface.FileTransmistObserver;
import model.infocenter.ClientUserInformations;


public class FileUploading implements Runnable
{
	private Socket dataDestination;
	private File fileToUpload;
	private FileTransmistObserver observer;
	
	public FileUploading( File file, Socket socket, FileTransmistObserver observer )
	{
		fileToUpload = file;
		dataDestination = socket;
		this.observer = observer;
	}

	@Override
	public void run() 
	{
		try 
		{
			System.out.println( "======= FileUploading: File Uploading Started! ======" );
			
			DataInputStream fileReader = new DataInputStream( new BufferedInputStream( new FileInputStream( fileToUpload ) ) );
	
			DataOutputStream dataWriter = new DataOutputStream( new BufferedOutputStream( dataDestination.getOutputStream() ) );
			
			byte[] buf = new byte[1024 * 10];
			int bytesReaded = 0;
			ClientUserInformations clientUser = ClientUserInformations.getInstance();
			try
			{
				while( (bytesReaded = fileReader.read(buf)) != -1 )
				{
					if ( clientUser.getCurRoomId() == -1 )
					{
						fileReader.close();
						dataDestination.close();
						return;
					}
					
					dataWriter.write(buf, 0, bytesReaded);
					dataWriter.flush();
				}
				
				fileReader.close();
				dataDestination.close();
				
				observer.update();
				System.out.println( "====== FileUploading: File Uploading Complished! =====" );
			}
			catch (Exception e)
			{
				fileReader.close();
				dataDestination.close();
				
				e.printStackTrace();
			}

		}
		catch ( Exception e ) 
		{
			observer.failed();
			e.printStackTrace();
		}
		
	}

}
